<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Mission;
use App\Models\UserWallet;
use Illuminate\Http\Request;

class MissionController extends Controller
{
    public function fistLogin()
    {
        $userId = request()->input('user_id', 0);
        $type = 'login';
        $qty = 1;
        $msg = '每日登陆奖励1个乒乓币';

        $today = Carbon::today();
        $firstLogin = Mission::where([['user_id',$userId],['created_at','>',$today]])->first();
        if($firstLogin){
            return response()->json([
                'recode' => 0,
                'msg' => '今天已经登陆过了',
            ]);
        }

        \DB::transaction(function () use ($userId, $type, $qty) {
            $userWallet = UserWallet::firstOrNew (
                ['user_id' => $userId], ['money' => 0]
            );
            $userWallet->money += $qty;
            $userWallet->save();
            //保存记录
            $mission = new Mission;
            $mission->user_id = $userId;
            $mission->qty = $qty;
            $mission->type = $type;
            $mission->save();
        });
        return response()->json([
            'recode' => 1,
            'msg' => $msg,
        ]);
    }
}
